package cn.itcast.bos.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.TakeTime;
import cn.itcast.bos.repository.CourierRepository;
import cn.itcast.bos.repository.FixedAreaRepository;
import cn.itcast.bos.repository.TakeTimeRepository;
import cn.itcast.bos.service.FixedAreaService;

@Service
@Transactional
public class FixedAreaServiceImpl implements FixedAreaService {

	@Autowired
	private FixedAreaRepository fixedAreaRepository;
	@Autowired
	private CourierRepository courierRepository;
	@Autowired
	private TakeTimeRepository takeTimeRepository;

	@Override
	public void save(FixedArea fixedArea) {
		fixedAreaRepository.save(fixedArea);
	}

	@Override
	public Page<FixedArea> pageQueryCondition(Specification<FixedArea> specification, Pageable pageable) {
		return fixedAreaRepository.findAll(specification, pageable);
	}

	@Override
	public void deleteFixedArea(String[] idArr) {
		for (String id : idArr) {
			fixedAreaRepository.delete(id);
		}
	}

	@Override
	public void associationCourierToFixedArea(String fixedAreaId, String courierId, String takeTimeId) {
		//通过定区id查询定区
		FixedArea fixedArea = fixedAreaRepository.findOne(fixedAreaId);
		//通过快递员id查找快递员
		Courier courier = courierRepository.findOne(Integer.parseInt(courierId));
		//通过收派时间id查询收派时间
		TakeTime takeTime = takeTimeRepository.findOne(Integer.parseInt(takeTimeId));
		//利用快照机制，将三者建立关系，这样当对象中的属性状态发生变化时会自动更新数据
		//快递员关联定区，定区来维护主键,多对多关系
		fixedArea.getCouriers().add(courier);
		//快递员关联收派时间，快递员来维护主键，一对多的关系
		courier.setTakeTime(takeTime);
	}

}
